package com.googlecode.bip.dao.mysql;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.List;
import javax.naming.NamingException;
import org.apache.log4j.Logger;
import com.googlecode.bip.dao.ReferentDAO;
import com.googlecode.bip.entity.IReferent;
import com.googlecode.bip.entity.impl.Referent;
import cx.ath.choisnet.sql.SQLTools;

/**
 *
 * @author Claude CHOISNET
 */
public class MySQLReferentDAO extends MySQLDAOBuilder<IReferent>
    implements ReferentDAO
{
    private final static transient Logger logger = Logger.getLogger( MySQLReferentDAO.class );
    private final static long serialVersionUID = 2L;

    @Override //Listable<IReferent>
    public IReferent newInstance(final ResultSet rSet )
        throws SQLException
    {
        return new Referent().set( rSet );
    }

    @Override
    public IReferent findReferent( int idreferent )
        throws NamingException, SQLException
    {
        return executeQuery(
                "SELECT * FROM `referentsview` WHERE `idreferent`="
                    + idreferent
                    + ";"
                );
    }

    @Override
    public List<IReferent> findReferents()
        throws NamingException, SQLException
    {
        return getList( "SELECT * FROM `referentsview`;" );
    }

    @Override
    public IReferent insertReferent(
            final String referentPublicName,
            final String referentPublicDescription,
            final String referentUserName,
            final String referentUserPassword
            )
        throws NamingException, SQLException
    {
        return executeQuery(
            "CALL `add_referent`( '"
                + SQLTools.parseFieldValue( referentUserName )
                + "', '"
                + SQLTools.parseFieldValue( referentUserPassword )
                + "', '"
                + SQLTools.parseFieldValue( referentPublicName )
                + "', '"
                + SQLTools.parseFieldValue( referentPublicDescription )
                + "');"
                );
    }

    @Override
    public boolean deleteReferent( final int idreferent )
        throws SQLException, NamingException
    {
        int r = doUpdate(
                "CALL `delete_referent`( '" + idreferent + "' );"
                );

        if( logger.isDebugEnabled() ) {
            logger.debug( "deleteReferent = " + r );
            }

        return true;
    }

}
